<template>
	<div class="table">
		<div class="table-warp">
			<el-table :data="tableData" ref="table" stripe v-bind="$attrs" v-loading="!isFirst&&loading" v-on="$listeners">
				<div slot="empty" style="height:100%;">
					<div :style="emptyHeight&&{'height':emptyHeight+'px'}" class="empty" v-if="!empty">
						<Empty isLoading></Empty>
					</div>
					<span v-else>{{empty}}</span>
				</div>
				<el-table-column align="center" fixed type="selection" v-if="$listeners['selection-change']" width="55"></el-table-column>
				<el-table-column :index="_indexMethod" align="center" fixed label="序号" type="index" width="55"></el-table-column>
				<slot></slot>
				<el-table-column :width="colWidth" align="center" fixed="right" label="操作" v-if="deleteData || $slots.operate">
					<template slot-scope="scope">
						<slot :row="scope.row" name="operate"></slot>
						<el-dropdown @command="handleCommand(scope.row,$event)" v-if="$slots.operate&&deleteData&&$slots.more">
							<el-button class="default-btn" icon="el-icon-arrow-down" type="text">更多操作</el-button>
							<el-dropdown-menu slot="dropdown">
								<slot name="more"></slot>
								<el-dropdown-item @click.native="_deleteData(scope.row)" icon="el-icon-delete">删除</el-dropdown-item>
							</el-dropdown-menu>
						</el-dropdown>
						<el-popconfirm :title="deleteTitle" @confirm="_deleteData(scope.row)" v-else-if="deleteData">
							<el-button class="delete" icon="el-icon-delete" slot="reference" type="text">删除</el-button>
						</el-popconfirm>
					</template>
				</el-table-column>
			</el-table>
		</div>
		<div class="pagination-warp" v-if="total>size">
			<el-pagination
				:current-page="current"
				:disabled="loading"
				:hide-on-single-page="total>size"
				:page-size="size"
				:page-sizes="pageSizes"
				:total="total"
				@current-change="_handleCurrentChange"
				@size-change="_handleSizeChange"
				background
				layout="total, sizes, prev, pager, next, jumper"
				v-if="needPagination"
			></el-pagination>
		</div>
	</div>
</template>
<script>
import Empty from '../Empty'
export default {
	components: {
		Empty
	},
	props: {
		/**
		 *  获取表格数据的方法，必填并且必须返回一个promise
		 * @param { Object } page - 组件调用该方法时会将分页数据传递过去
		 * @param { Boolean } needCache - 标识符，标识组件调用该方法时，该方法是否可以设置缓存（目前分页切换和查询时可以设置缓存）
		 * @returns {Promise} 返回一个parmise
		 */
		getTableData: {
			type: Function,
			required: true
		},
		/**
		 *  请求完数据后可以对数据进行过滤
		 */
		filterData: {
			type: Function
		},

		/**
		 * 分页pageSize
		 */
		pageSizes: {
			type: Array,
			default: function () {
				return [5, 10, 20, 50]
			}
		},
		/**
		 * 删除数据提示语
		 */
		deleteTitle: {
			type: String,
			default: '确认删除该项数据吗？'
		},
		/**
		 * 删除数据的方法
		 * @returns {Promise} 返回一个parmise
		 */

		deleteData: {
			type: Function
		},
		/**
		 * 操作列的宽度
		 */
		colWidth: {
			type: Number,
			default: 80
		},
		/**
		 * 空数据文本
		 */
		emptyText: {
			type: String,
			default: '暂无数据'
		}
	},
	data() {
		return {
			tableData: [],
			current: 1,
			size: 10,
			total: 0,
			needPagination: false,
			loading: false,
			empty: '',
			emptyHeight: null,
			isFirst: true // 表明组件是否是第一次初始化，第一次调接口
		}
	},
	mounted() {
		// 如果设置了高度为100%则默认加载框的高度也是100%,否则设置默认400
		if (!this.$attrs.height) {
			this.emptyHeight = 400
		}

		this.fetchData()
	},
	methods: {
		_handleCurrentChange(val) {
			this.current = val
			this.fetchData(1)
		},
		_handleSizeChange(val) {
			this.size = val
			this.current = 1
			this.fetchData()
		},
		_indexMethod(index) {
			return (this.current - 1) * this.size + index + 1
		},
		async _deleteData(row) {
			await this.deleteData(row)
			if (this.tableData.length === 1) {
				if (this.current > 1) {
					this.current--
					this.fetchData()
					return
				}
			}
			this.fetchData()
		},
		async fetchData(needCache) {
			try {
				const res = await this.getTableData(
					{
						current: this.current,
						size: this.size
					},
					needCache === 1 // 告诉子组件，这次调用可以用缓存
				)

				if (res.records) {
					this.needPagination = true
					this.tableData = this.filterData ? this.filterData(res.records) : res.records
					if (!this.tableData.length) {
						this.empty = this.emptyText || '暂无数据'
					}
					this.total = res.total
				} else {
					this.tableData = this.filterData ? this.filterData(res) : res
					if (!res.length) {
						this.empty = this.emptyText || '暂无数据'
					}
				}
			} catch (error) {
				this.empty = '暂无数据'
			}
			if (this.isFirst) {
				this.isFirst = false // 表格第一次加载的loading由empty提供，后续loading由loading字段展示
			}
		},
		/**
		 * @description 刷新表格，用于给父组件ref调用
		 * @param { Boolean } isRest - 是否重置到第一页
		 */
		refresh(isRest = false) {
			if (isRest) {
				this.current = 1
			}
			this.fetchData()
		},
		/**
		 * @description 表格搜索，用于给父组件ref调用
		 */
		search() {
			this.current = 1
			this.fetchData(1)
		},

		/**
		 * @description 表格实例，用于给父组件ref调用
		 */
		GetTable() {
			return this.$refs.table
		},
		handleCommand(item, key) {
			/**
			 * @description 点击更多操作按钮触发
			 * @event command
			 * @type {Event}
			 */
			this.$emit('command', item, key)
		}
	}
}
</script>
<style lang="scss" scoped>
.table {
	display: flex;
	flex-direction: column;
	.empty {
		height: 100%;
	}
	.table-warp {
		flex: 1;
		height: 0;
		:v-deep .default-btn {
			color: $color-warn;
		}
		:v-deep .el-dropdown {
			margin-left: 10px;
		}
		:v-deep .el-table__fixed,
		:v-deep .el-table__fixed-right {
			&::before {
				height: 0;
			}
		}
	}
	.delete {
		color: $color-err;
		margin-left: 10px;
	}
	.pagination-warp {
		text-align: right;
		margin-top: $margin;
		:v-deep .el-pagination__total {
			float: left;
		}
	}
}
</style>
